package com.lyf.emp.Utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;

public class MyBatisUtils {
    //获得sqlsession工厂
    private static SqlSessionFactory factory;
    //创建ThreadLocal绑定当前线程中的sqlSession对象
    private static final ThreadLocal<SqlSession> t = new ThreadLocal<>();
    //静态代码块（只访问一次）
    static {
        //resources  获得读取MyBatis配置文件的流对象
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            //构建sqlsession连接对象的工厂
            factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static SqlSession openSession(){
        SqlSession session = t.get();
        if (session==null) {
            session=factory.openSession();
            t.set(session);
        }
        return session;
    }
    //释放连接
    public static void closeSession(){
        SqlSession session = t.get();
        session.close();
        t.remove();
    }
    //提交事务
    public static void commit(){
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }

    //回滚事务
    public static void rollback(){
        SqlSession session = openSession();
        session.rollback();
        closeSession();
    }
    //获得接口实现类对象
    public static <T> T getMapper(Class<T> c){
        return openSession().getMapper(c);
    }
}
